//
//  Network.swift
//  ChatTest
//
//  Created by kangqiao on 2021/9/3.
//
import UIKit
import AFNetworking
import KQChatSDK
open class Network: NSObject {
    
    // MARK: - Request


    /// POST请求
    /// - Parameters:
    ///   - urlString: URL地址
    ///   - parameters: 参数
    ///   - headers: httpHeaders
    ///   - timeoutInterval: 超时时间
    ///   - success: 成功
    ///   - failure: 失败
    /// - Returns: URLSessionDataTask
    public func post(success: ((_ task: URLSessionDataTask, _ responseObject: Any?) -> Void)?,
                   failure: ((_ task: URLSessionDataTask?, _ error: NSError?) -> Void)?)
    {
        let manager = AFHTTPSessionManager()
        manager.requestSerializer = AFJSONRequestSerializer()
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//        manager.responseSerializer.acceptableContentTypes = ["application/json"]
        let  favoriteGenres: Set = ["application/json"]
        manager.responseSerializer.acceptableContentTypes = favoriteGenres
        manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let authToken: String? = UserDefaults.standard.object(forKey: "WFC_APPSERVER_AUTH_TOKEN") as? String
        //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程
        if authToken?.count != 0 && authToken?.count != nil {
            manager.requestSerializer.setValue(authToken, forHTTPHeaderField: "authToken")
        } else {
            let cookiesdata: Data? = UserDefaults.standard.object(forKey: "WFC_APPSERVER_COOKIES") as? Data
            if cookiesdata != nil {
                let cookies: NSArray? = NSKeyedUnarchiver.unarchiveObject(with: cookiesdata!) as? NSArray
                cookies?.forEach({ cookie in
                    HTTPCookieStorage.shared.setCookie((cookie as? HTTPCookie)!)
                })
                
            }
        }
        
        let clientId = WFCCNetworkService.sharedInstance().getClientId()
        let  parame = ["mobile":"15638259091","clientId":clientId,"code":"66666","platform":"1"]
       
        let string = self.dicValueString(parame as [String : Any])
//        let str = "http://47.93.181.13:9030/login?mobile=15638259091&code=66666&platform=1&clientId\(clientId ?? "")"
        let str = "http://47.93.181.13:9030/login"

        manager.post(str, parameters: parame, headers: nil) { progress in
            
        } success: { task, responseObject in
            var appToken: String = "authToke"
            if ((task.response?.isKind(of: HTTPURLResponse.self)) != nil) {
                let r = task.response as! HTTPURLResponse
                appToken = r.allHeaderFields["authToken"] as? String ?? ""
            }
            if appToken.count > 0 {
                UserDefaults.standard.setValue(appToken, forKey: "WFC_APPSERVER_AUTH_TOKEN")
            } else {
                let url = URL(string: "")
                let cookies = HTTPCookieStorage.shared.cookies(for: url!)
            let data = NSKeyedArchiver.archivedData(withRootObject: cookies ?? HTTPCookie())
                UserDefaults.standard.setValue(data, forKey: "WFC_APPSERVER_COOKIES")
            }
            let dict: NSDictionary = responseObject as! NSDictionary
            success!(task,dict)
            
        } failure: { task, error in
            failure!(task, error as NSError)
        }

        
        
    }

    func dicValueString(_ dic:[String : Any]) -> String?{

        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])

        let str = String(data: data!, encoding: String.Encoding.utf8)

        return str

    }

    
    func printRequest(method: String, url: String?, body: Any?, header: [String: String]) {
        
    }
    
}

